package me.liuyu2783.dubbo.sample.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;

/**
 * me.liuyu2783.dubbo.sample.netty
 *
 * @author liuyu2783
 * @date 2020-3-3
 */
public class NettyServer {

    public void start(int port){
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.channel(NioServerSocketChannel.class);
        EventLoopGroup mainGroup = new NioEventLoopGroup(1);
        EventLoopGroup workGroup = new NioEventLoopGroup(8);
        serverBootstrap.group(mainGroup, workGroup);
        serverBootstrap.childHandler(new ChannelInitializer<NioSocketChannel>() {
            @Override
            protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                //初始化netty的管道
                nioSocketChannel.pipeline().addLast("http-code", new HttpRequestDecoder());
                nioSocketChannel.pipeline().addLast("http-aggregator", new HttpObjectAggregator(1));
                nioSocketChannel.pipeline().addLast("http-encode", new HttpResponseEncoder());
                nioSocketChannel.pipeline().addLast("servlet", new NettyServerHandler());
            }
        });
        try {
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            System.out.println("服务已开启");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
